#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QWidget>
#include <QVBoxLayout>
#include "addtaskdialog.h"
#include <QMacStyle>
#include <QFileInfo>
#include <QMessageBox>


MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent)
{
    resize(800, 500);
    setWindowFlags(Qt::MSWindowsFixedSizeDialogHint);

    QWidget *w = new QWidget(this);
    w->setLayout(new QVBoxLayout());
    setCentralWidget(w);

    QPushButton *addTaskBtn = new QPushButton("+ New Task", this);
    addTaskBtn->setMaximumWidth(100);
    connect(addTaskBtn, SIGNAL(clicked()), this, SLOT(addTaskBtnClicked()));

    centralWidget()->layout()->setAlignment(Qt::AlignTop);
    centralWidget()->layout()->addWidget(addTaskBtn);

    dbSetting = new DataBaseSetting(this);
    if(!dbSetting->init()){
        QMessageBox *mb = new QMessageBox(QMessageBox::Information, "Attention!",
                                          "Last session data can not be loaded!", QMessageBox::Yes, this);
        mb->exec();
    }

    downloadTable = new DownloadTable(dbSetting->dwnTableName(), dbSetting->dwnTableColumn(), dbSetting->dwnTableColumnType());
    centralWidget()->layout()->addWidget(downloadTable);

    urlTable = new UrlTable(dbSetting->urlTableName(), dbSetting->urlTableColumn(), dbSetting->urlTableColumnType());

    downloader = new Downloader();
    connect(downloader, SIGNAL(progressChanged(QString, int)), downloadTable,
            SLOT(taskProgressChanged(QString, int)));

    show();

    int rowCount = downloadTable->rowCount();

    if(rowCount > 0){
        if(rowCount == urlTable->rowCount()){
            QMessageBox *mb = new QMessageBox(QMessageBox::Question,
                                              "Restart", "Restart last session download?");
            mb->setStandardButtons(QMessageBox::Yes | QMessageBox::No);
            if(mb->exec() == QMessageBox::Yes){
                QVector<DownloadTask*> tasks;
                dbSetting->getTaskForDownload(tasks);

                for(int i = 0; i < tasks.size(); ++i){
                    downloader->append(tasks[i]);
                }
            }
        }else{
            QMessageBox *mb = new QMessageBox(QMessageBox::Question,
                                              "Restart", "Restart last session is not possible due to errors in configuring");
            mb->setStandardButtons(QMessageBox::Ok);
            mb->exec();
        }


    }
}

void MainWindow::addTaskBtnClicked(){
    AddTaskDialog *addTaskDlg = new AddTaskDialog();
    if(addTaskDlg->exec()){

        DownloadTask *task = new DownloadTask(addTaskDlg->url(), addTaskDlg->rename(),
                      addTaskDlg->savePath(), addTaskDlg->priority());

        downloadTable->addRow(task);
        urlTable->addRow(task);
        downloader->append(task);
    }
}

MainWindow::~MainWindow()
{
}
